<?php

namespace App\Api\Controllers\Dong_Guan;


class PayController extends BaseController
{
    //付款码支付
    public function scan_pay($data)
    {
        try {
            $payData = [
                'service' => 'unified.trade.micropay',
                'mch_id' => $data['mch_id'],//商户号
                'out_trade_no' => $data['out_trade_no'],//商户订单号
                'total_fee' => $data['total_amount'] * 100,//总金额
                'body' => $data['goods_desc'],//商品描述
                'mch_create_ip' => $_SERVER['REMOTE_ADDR'],//订单生成的机器 IP
                'auth_code' => $data['auth_code'],//授权码
                'op_device_id' => $data['op_device_id'],//终端编号
                'terminal_info' => json_encode([
                    'device_type' => 12,
                    'terminal_id' => $data['op_device_id']
                ]),//终端信息
                'version' => '2.0',
                'sign_type' => 'MD5',
                'nonce_str' => mt_rand(999, 9999),
            ];
            if (isset($data['goods_detail']) && is_array($data['goods_detail']) && count($data['goods_detail']) > 0) {
                $payData['goods_detail'] = json_encode($data['goods_detail']);
            }
            $xml = $this->curlPost($this->baseUrl, '', $payData, $data['private_key']);
            $result = $this->xml_decode($xml);
            if ($result['status'] != '0') {
                $this->_exception($result['message']);
            }
            if (!$this->verification($result, $data['private_key'])) {
                $this->_exception('签名校验不通过');
            }
            if ($result['result_code'] == '1' && $result['need_query']=='Y') {
                return [
                    'status' => 3,
                    'message' => '交易进行中',
                    'data' => $result
                ];
            }
            if ($result['result_code'] != '0') {
                $this->_exception($result['err_msg']);
            }
            if ($result['pay_result'] == 0) {
                return [
                    'status' => 1,
                    'message' => '支付成功',
                    'data' => [
                        'total_amount' => bcdiv($result['total_fee'], 100, 2),
                        'pay_time' => date('Y-m-d H:i:s', strtotime($result['time_end'])),
                        'out_trade_no' => $result['out_transaction_id'],
                    ]
                ];
            }
            return [
                'status' => 2,
                'message' => $result['result_msg']
            ];
        } catch (\Exception $ex) {
            return [
                'status' => 2,
                'message' => $ex->getMessage(),
            ];
        }
    }

    //二维码支付
    public function send_qr($data)
    {
        try {
            $payData = [
                'service' => 'unified.trade.native',
                'mch_id' => $data['mch_id'],//商户号
                'out_trade_no' => $data['out_trade_no'],//商户订单号
                'total_fee' => $data['total_amount'] * 100,//总金额
                'body' => $data['goods_desc'],//商品描述
                'sub_openid' => $data['open_id'],//用户openid
                'sub_appid' => $data['appid'],//公众账号或小程序ID
                'mch_create_ip' => $_SERVER['REMOTE_ADDR'],//订单生成的机器 IP
                'notify_url' => $data['notify_url'],//通知地址
                'version' => '2.0',
                'sign_type' => 'MD5',
                'nonce_str' => mt_rand(999, 9999),
            ];
            $xml = $this->curlPost($this->baseUrl, '', $payData, $data['private_key']);
            $result = $this->xml_decode($xml);
            if ($result['status'] != '0') {
                $this->_exception($result['message']);
            }
            if (!$this->verification($result, $data['private_key'])) {
                $this->_exception('签名校验不通过');
            }
            if ($result['result_code'] != '0') {
                $this->_exception($result['err_msg']);
            }
            return [
                'status' => 1,
                'message' => 'Ok',
                'data' => $result,
            ];
        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage(),
                'data' => [],
            ];
        }
    }

    public function order_query($data)
    {
        try {
            $queryData = [
                'service' => 'unified.trade.query',
                'mch_id' => $data['mch_id'],//商户号
                'out_trade_no' => $data['out_trade_no'],//商户订单号
                'version' => '2.0',
                'sign_type' => 'MD5',
                'nonce_str' => mt_rand(999, 9999),
            ];
            $xml = $this->curlPost($this->baseUrl, '', $queryData, $data['private_key']);
            $result = $this->xml_decode($xml);
            if ($result['status'] != '0') {
                $this->_exception($result['message']);
            }
            if (!$this->verification($result, $data['private_key'])) {
                $this->_exception('签名校验不通过');
            }
            if ($result['result_code'] != '0') {
                $this->_exception($result['err_msg']);
            }
            if (in_array($result['trade_state'], ['SUCCESS'])) {
                return [
                    'status' => 1,
                    'message' => '交易成功',
                    'data' => [
                        'total_amount' => bcdiv($result['total_fee'], 100, 2),
                        'pay_time' => date('Y-m-d H:i:s', strtotime($result['time_end'])),
                        'out_trade_no' => $result['out_transaction_id'],
                    ]
                ];
            }
            if (in_array($result['trade_state'], ['CLOSED', 'REVOKED', 'REVERSE', 'PAYERROR'])) {
                return [
                    'status' => 3,
                    'message' => '支付异常',
                ];
            }
            return [
                'status' => 2,
                'message' => '支付中'
            ];
        } catch (\Exception $ex) {
            return [
                'status' => 2,
                'message' => $ex->getMessage(),
            ];
        }
    }

    public function refund($data)
    {
        try {
            $queryData = [
                'service' => 'unified.trade.refund',
                'mch_id' => $data['mch_id'],//商户号
                'op_user_id' => $data['mch_id'],//收银员
                'out_trade_no' => $data['out_trade_no'],//商户订单号
                'out_refund_no' => $data['refund_no'],//商户退单号
                'total_fee' => $data['total_amount'] * 100,
                'refund_fee' => $data['refund_amount'] * 100,
                'version' => '2.0',
                'sign_type' => 'MD5',
                'nonce_str' => mt_rand(999, 9999),
            ];
            $xml = $this->curlPost($this->baseUrl, '', $queryData, $data['private_key']);
            $result = $this->xml_decode($xml);
            if ($result['status'] != '0') {
                $this->_exception($result['message']);
            }
            if (!$this->verification($result, $data['private_key'])) {
                $this->_exception('签名校验不通过');
            }
            if ($result['result_code'] != '0') {
                return [
                    'status' => 2,
                    'message' => '退款失败'
                ];
            }
            return [
                'status' => 1,
                'message' => '退款成功',
                ''
            ];
        } catch (\Exception $ex) {
            return [
                'status' => 2,
                'message' => $ex->getMessage(),
            ];
        }
    }

    public function refund_query($data)
    {
        try {
            $queryData = [
                'service' => 'unified.trade.refundquery',
                'mch_id' => $data['mch_id'],//商户号
                'out_trade_no' => $data['out_trade_no'],//商户订单号
                'out_refund_no' => $data['refund_no'],//商户退单号
                'version' => '2.0',
                'sign_type' => 'MD5',
                'nonce_str' => mt_rand(999, 9999),
            ];
            $xml = $this->curlPost($this->baseUrl, '', $queryData, $data['private_key']);
            $result = $this->xml_decode($xml);
            if ($result['status'] != '0') {
                $this->_exception($result['message']);
            }
            if (!$this->verification($result, $data['private_key'])) {
                $this->_exception('签名校验不通过');
            }
            if ($result['result_code'] == '0') {
                for ($i = 0; $i <= $result['refund_count']; $i++) {
                    if ($result['out_refund_no_' . $i] == $data['refund_no']) {
                        if ($result['refund_status_' . $i] == 'SUCCESS') {
                            return [
                                'status' => 1,
                                'message' => '退款成功',
                                'data' => [
                                    'refund_amount' => $result['refund_fee_' . $i],
                                    'refund_time' => date('Y-m-d H:i:s', strtotime($result['refund_time_' . $i]))
                                ]
                            ];
                        }
                        if ($result['refund_status_' . $i] == 'PROCESSING') {
                            return [
                                'status' => 2,
                                'message' => '退款中'
                            ];
                        }
                        if (in_array($result['refund_status_' . $i], ['FAIL', 'NOTSURE', 'CHANGE'])) {
                            $this->_exception('退款失败');
                        }
                    }
                }

            }
            return [
                'status' => 0,
                'message' => '退款失败'
            ];
        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage(),
            ];
        }
    }

}
